package com.longrise.android.byjk.plugins.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.main.MainActivity;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.ActivityUtil;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.InputBoxView;

import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 登录页面
 * <p/>
 * <p/>
 * detailed comment
 *
 * @author xkj 2015-12-31
 * @see
 * @since 1.0
 */
public class LoginActivity extends BaseActivity implements OnClickListener, TextWatcher {

    protected static final String TAG = "LoginActivity";

    private Button mLoginBtn;

    private InputBoxView mIBVusername;

    private InputBoxView mIBVpassword;

    private TextView mTvyhzc;

    private TextView mTvwjmm;

    private EntityBean fbean;
    private Toolbar mToolbar;
    private TextView mTvTitle;
    private RelativeLayout mRlright;
    private TextView mTvTitle_right;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login_layout;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        mIBVpassword.setText("");
    }

    @Override
    public void initView() {
        ActivityUtil.removeActivity(this);
        ActivityUtil.finishAllAcivity();
        ActivityUtil.addActivity(this);

        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        mToolbar.setNavigationIcon(null);
        setSupportActionBar(mToolbar);
        mTvTitle = (TextView) findViewById(R.id.bb_toolbar_middle_title);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText(AppUtil.getString(R.string.login_title));
        mRlright = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl_tv);
        mTvTitle_right = (TextView) findViewById(R.id.iv_toolbar_right_tv);
        mTvTitle_right.setText(AppUtil.getString(R.string.login_right_tv));
        mRlright.setVisibility(View.VISIBLE);

        mLoginBtn = (Button) this.findViewById(R.id.loginBtn);
        mLoginBtn.setEnabled(false);

        mIBVusername = (InputBoxView) findViewById(R.id.login_username);
        mIBVpassword = (InputBoxView) findViewById(R.id.login_password);
        mTvyhzc = (TextView) findViewById(R.id.login_yhzc);

        mTvwjmm = (TextView) findViewById(R.id.login_wjmm);

        EditText etusername = mIBVusername.getEditText();
        initEvent();
        initNameEt(etusername);


        //当前Activity存在上层跳转时，在onCreate()添加页面跟踪更为准确
        Tracker_Google.getInstance().addGoogleScreenName("登录");
    }

    /**
     * 限制用户名只能输入18个字
     */
    private void initNameEt(EditText etusername) {
        etusername.setInputType(InputType.TYPE_CLASS_TEXT);
        etusername.setText(CacheUtils.getString(Control.USERNAME, null));
        etusername.setSelection(etusername.getText().length());
        etusername.setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                               int dstart, int dend) {
                        String dests = dest.toString(); //已经显示的字符串
                        int destslen = 0;
                        if (!TextUtils.isEmpty(dests)) {
                            destslen = dests.length();
                        }
                        String s = dest.toString() + source;
                        if (destslen >= 18) {  //已经显示的字符串长度如果大于18 则不能输入
                            return "";
                        } else {
                            if (s.length() <= 18) { //要输入的字符串长度+已经显示的字符串长度<=18
                                return source;
                            } else {
                                if (!TextUtils.isEmpty(source)) {
                                    String inputs = source.toString().substring(0, 18 - destslen);
                                    return inputs;
                                }
                            }
                        }
                        return "";
                    }
                }
        });

    }


    public void initEvent() {
        mRlright.setOnClickListener(this);
        mLoginBtn.setOnClickListener(this);
        mTvyhzc.setOnClickListener(this);
        mTvwjmm.setOnClickListener(this);
        mIBVusername.setRightClickMode(InputBoxView.USERIF);
        mIBVpassword.setRightClickMode(InputBoxView.PASSWORD);
        mIBVpassword.setTextMode(InputBoxView.PASSWORD);

        mIBVusername.getEditText().addTextChangedListener(this);
        mIBVpassword.getEditText().addTextChangedListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn: // 登录
                checkLoginParams();
                break;

            case R.id.login_yhzc: // 用户注册
                toRegister();
                Tracker_Google.getInstance().addEvent("Log-page", "Hit-register", "用户注册");
                break;

            case R.id.login_wjmm: // 找回密码
                loadConfrimCode();
                toForgetPassword();
                Tracker_Google.getInstance().addEvent("Log-page", "Hit-forgetpw", "忘记密码");
                break;

            case R.id.bb_toolbar_right_rl_tv: //手机号登录 快捷登录
                startActivity(LoginByPhnumActivity.class);
                Tracker_Google.getInstance().addEvent("Log-page", "fast-login-click", "快捷登录");
                break;
            default:
                break;
        }
    }

    /**
     * 检查登录所需的用户名密码
     */
    public void checkLoginParams() {
        String musername = mIBVusername.getText();
        if (musername == null || musername.equals("")) {
            DZZWTools.showToast(LoginActivity.this, "身份证号或用户账号不能为空", 0);
            return;
        }
        String password =  mIBVpassword.getText();
        if (password == null || password.equals("")) {
            DZZWTools.showToast(LoginActivity.this, "密码不能为空", 0);
            return;
        }
        toLogin(musername, password);
    }

    /**
     * 普通登录
     */
    public void toLogin(final String username, String password) {
        final EntityBean bean = new EntityBean();
        bean.set("username", username);
        bean.set("password", password);
        fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(LoginActivity.this);
        mLoginBtn.setClickable(false);
        UserController.getInstance().login(UserController.LOGIN, this, fbean, new UserCallback() {
            @Override
            public void onSuccess(int status, String des) {
                //将用户名保存本地 方便下次进入软件时 自动填写
                CacheUtils.setString(Control.USERNAME, username);
                DZZWTools.showToast(LoginActivity.this, des, 2 * 1000);
                if (status == UserCallback.HOME_PAGE) {
                    LoginActivity.this.startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    LoginActivity.this.finish();
                }
            }

            @Override
            public void onFail(String des) {
                DZZWTools.showToast(LoginActivity.this, des, 2 * 1000);
            }

            @Override
            public void onFinish() {
                DZZWTools.dismissDialog(null);
                mLoginBtn.setClickable(true);
            }
        });
    }

    /**
     * 用户注册
     */
    public void toRegister() {
        startActivity(RegisterActivity.class);
        //LoginActivity.this.startActivity(new Intent(LoginActivity.this, EasyRegistActivity.class));
    }

    /**
     * 找回密码
     */
    public void toForgetPassword() {
        EntityBean bean = new EntityBean();
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_sVerification", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    Integer resultstate = bean.getInt("resultstate");
                    String resultdesc = bean.getString("resultdesc");
                    if (resultstate == 1) {
                        startActivity(ForgetPasswordActivity.class);
                    } else {
                        showToast(resultdesc);
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                showToast(AppUtil.getString(R.string.networkerror));
            }

            @Override
            public void onFinished(String key, String service) {
                dismissLoadingDialog();
            }
        });


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Tracker_Google.getInstance().addEvent("log_page", "Login-back", "登录页面，按back键退出");
            finish();
            System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * sjz加入，leap验证码图片session相关错误，具体咨询hkb
     */
    private void loadConfrimCode() {
        new Thread() {
            public void run() {
                try {
                    // 获取连接
                    HttpURLConnection conn = (HttpURLConnection) new URL(UrlConstants.VFCODE_URL).openConnection();
                    conn.setConnectTimeout(30 * 1000);// 设置连接服务器超时时间
                    conn.setReadTimeout(30 * 1000);// 设置读取响应超时时间
                    // 连接网络
                    conn.connect();
                    // 获取响应码
                    int code = conn.getResponseCode();
                    if (200 == code) {
                        String cookie = conn.getHeaderField("Set-Cookie");
                        LoadDataManager.getInstance().setCookie(UrlConstants.VFCODE_URL, cookie);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //-------------输入框字符变化----------------
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean b = checkText();
        if (b) {
            mLoginBtn.setEnabled(true);
        } else {
            mLoginBtn.setEnabled(false);
        }
    }
    //------------------------------------------


    /**
     * 检查是否全部填写
     *
     * @return 全部有填写 返回true
     */
    private boolean checkText() {
        //用户名
        String username = mIBVusername.getText();
        if (TextUtils.isEmpty(username)) {
            return false;
        }
        //密码
        String password = mIBVpassword.getText();
        if (TextUtils.isEmpty(password)) {
            return false;
        }
        return true;
    }

}
